package com.yunfeng.supercall.bean;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.graphics.Color;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.ly.library.stickyadpter.BaseStickyBean;
import com.ly.quickdev.library.adapter.ListBaseAdapter.ViewHolder;
import com.ly.quickdev.library.utils.ShouZiMu;
import com.t9search.model.PinyinUnit;
import com.t9search.util.PinyinUtil;
import com.yunfeng.supercall.R;
import com.yunfeng.supercall.activity.MainActivity;
import com.yunfeng.supercall.app.AppContext;
import com.yunfeng.supercall.iface.Searchable;

/**
 * 联系人实体类基类，提供公用方法和属性
 * 
 * @author 洋
 * 
 */
public class ContactsBaseBean implements Searchable, BaseStickyBean,
Comparable<ContactsBaseBean>, Parcelable {
	public static final int TYPE_SUPER_CONTACTS = 0;// 超友
	public static final int TYPE_SYSTEM_CONTACTS = 1;// 默认的一些内容，在顶部，比如新的超友，超友分组
	public static final int TYPE_NORMAL_CONTACTS = 2;// 手机里边的通讯录。不是从这个软件添加的
	public static final int TYPE_MY_CIRCLE = 3;// 圈子
	public static final int TYPE_FRIENDS_GROUP = 4;// 朋友分组
	public static final int TYPE_LEVEL = 5;
	public static final String RED = "#ff0000";
	private CharSequence superNumber;

	public int getContactsType() {
		return type;
	}
	
	private String real_name;
	private String phone;
	private String photo;
	private int userid;
	private int type;
	private long lastChatTime;
	private boolean unread;
	private int unreadCount;
	private String suid;
	private String onlineday;// 在线时间
	private List<PinyinUnit> mNamePinyinUnits = new ArrayList<PinyinUnit>(); // save
	// the
	// mName
	// converted
	// to
	// Pinyin characters.

	private SearchByType mSearchByType; // Used to save the type of search
	private StringBuffer mMatchKeywords = new StringBuffer(); // Used to save
	// the type of
	// Match
	

	public static final Parcelable.Creator<ContactsBaseBean> CREATOR = new Creator<ContactsBaseBean>() {

		@Override
		public ContactsBaseBean createFromParcel(Parcel source) {
			// TODO Auto-generated method stub
			ContactsBaseBean mContactsBaseBean = new ContactsBaseBean();
			mContactsBaseBean.real_name = source.readString();
			if(mContactsBaseBean.real_name==null) mContactsBaseBean.real_name="";
			mContactsBaseBean.nick_name = source.readString();
			if(mContactsBaseBean.nick_name==null) mContactsBaseBean.nick_name="";
			
			mContactsBaseBean.phone = source.readString();
			if(mContactsBaseBean.phone==null) mContactsBaseBean.phone="";
			
			mContactsBaseBean.photo = source.readString();
			if(mContactsBaseBean.photo==null) mContactsBaseBean.photo="";
			
			mContactsBaseBean.userid = source.readInt();
			mContactsBaseBean.type = source.readInt();
			mContactsBaseBean.sucolor = source.readInt();
			mContactsBaseBean.unread = source.readInt() == 0? false : true;
			mContactsBaseBean.unreadCount = source.readInt();
			
			mContactsBaseBean.suid = source.readString();
			if(mContactsBaseBean.suid==null) mContactsBaseBean.suid="";
			
			mContactsBaseBean.onlineday = source.readString();
			if(mContactsBaseBean.onlineday==null) mContactsBaseBean.onlineday="";
			
			return mContactsBaseBean;
		}

		@Override
		public ContactsBaseBean[] newArray(int size) {
			// TODO Auto-generated method stub
			return  new ContactsBaseBean[size];
		}
		
	};
	
	
	
	// Keywords.(name or phoneNumber)

	public int getUnreadCount() {
		return unreadCount;
	}

	public StringBuffer getMatchKeywords() {
		return mMatchKeywords;
	}

	public void setMatchKeywords(String words) {
		mMatchKeywords.delete(0, words.length());
		mMatchKeywords.append(words);
	}

	public String getSuid() {
		return suid;
	}

	public void setSuid(String suid) {
		this.suid = suid;
	}

	public void setUnreadCount(int unreadCount) {
		this.unreadCount = unreadCount;
	}

	public long getLastChatTime() {
		return lastChatTime;
	}

	public boolean isUnread() {
		return unread;
	}

	public void setUnread(boolean unread) {
		this.unread = unread;
	}

	public void setLastChatTime(long lastChatTime) {
		this.lastChatTime = lastChatTime;
	}

	public static final int TYPE_PERSONAL = 1;
	public static final int TYPE_ENTERPRISE = 2;

	// public static final Creator<ContactsBase> CREATOR = new
	// Creator<ContactsBase>() {
	//
	// @Override
	// public ContactsBase[] newArray(int size) {
	// // TODO Auto-generated method stub
	// return new ContactsBase[size];
	// }
	//
	// @Override
	// public ContactsBase createFromParcel(Parcel source) {
	// // TODO Auto-generated method stub
	// return new ContactsBase(source);
	// }
	// };

	private int sucolor;

	public int getSucolor() {
		return sucolor;
	}

	public void setSucolor(int sucolor) {
		this.sucolor = sucolor;
	}

	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}

	public String getOnlineday() {
		return onlineday;
	}

	public void setOnlineday(String onlineday) {
		this.onlineday = onlineday;
	}

	/**
	 * 设置单行的
	 * 
	 * @param v
	 * @param base
	 */
	public static final void setupSingleLineContactsView(View v,
			ContactsBaseBean base) {
		TextView tv = ViewHolder.get(v, R.id.tv);
		tv.setTextColor(v.getResources().getColor(android.R.color.black));
		// tv.setOnEditorActionListener(new OnEditorActionListener() {
		//
		// @Override
		// public boolean onEditorAction(TextView v, int actionId, KeyEvent
		// event) {
		// // TODO Auto-generated method stub
		// if(event.getKeyCode()==KeyEvent.KEYCODE_DEL){
		//
		// }
		// return false;
		// }
		// });
		final ImageView iv = ViewHolder.get(v, R.id.iv);
		if (base instanceof SystemContactsBean) {
			iv.setImageResource(((SystemContactsBean) base).getImgId());
			String name = base.getNick_name();
			if (TextUtils.isEmpty(name)) {
				name = base.getReal_name();
			}
			tv.setText(name);
		} else if (base instanceof SuperFriendsBean) {
			try {
				tv.setTextColor(Color.parseColor(MainActivity.LEVEL_COLOR_MAPS
						.get(((SuperFriendsBean) base).getSucolor() + "")
						.getColor()));
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (!TextUtils.isEmpty(base.getPhoto())) {
				AppContext.displayImgWithDefault1(iv, base.getPhoto());
			} else {
				iv.setImageBitmap(AppContext.BITMAP);
			}
			if (base instanceof RecentCallsBean) {
				tv.setText(((RecentCallsBean) base).getNick_name());
				AppContext.displayImgWithDefault1(iv, base.getPhoto());
			} else {
				String name = base.getNick_name();
				if (TextUtils.isEmpty(name)) {
					name = base.getReal_name();
				}
				tv.setText(name);
			}
		} else if (base instanceof MyCircleBean) {
			MyCircleBean myCircle = (MyCircleBean) base;
			AppContext.displayImgWithDefault1(iv, myCircle.getPhoto());
			tv.setText(myCircle.getName());
		}
		TextView level = ViewHolder.get(v, R.id.level);
		if (level != null) {
			try {
				level.setText(MainActivity.LEVEL_MAPS.get(((SuperFriendsBean) base)
						.getLevel() + ""));
				level.setTextColor(Color
						.parseColor(MainActivity.LEVEL_COLOR_MAPS.get(
								((SuperFriendsBean) base).getSucolor() + "")
								.getColor()));
			} catch (Exception e) {
			}
		}
	}


	public void setSuperNumber(CharSequence superNumber) {
		this.superNumber = superNumber;
	}

	public CharSequence getWhiteSuperNumber() {
		String number = suid;
		if (getType() == TYPE_PERSONAL) {
			if(number.length() > 0) {
				number = number.substring(0, number.length() - 1);
				number = replaceTextColor(number, number, "ffffff");
				number += replaceTextColor("8", "8", RED).toString();
			}

		} else {
			if(number.length() > 0) {
				number = number.substring(1, number.length());
				number = replaceTextColor(number, number, "ffffff");
				number = replaceTextColor("0", "0", RED) + number;
			}
		}
		return Html.fromHtml(number);
	}

	public CharSequence getSuperNumber() {
		// if (superNumber == null) {
		if (sucolor == 0) {
			String number = suid;
			if (!MainActivity.LEVEL_COLOR_MAPS.isEmpty()) {
				try {
					if (getType() == TYPE_PERSONAL) {
						number = number.substring(0, number.length() - 1);
						number += replaceTextColor("8", "8", RED).toString();
					} else {
						number = number.substring(1, number.length());
						number = replaceTextColor("0", "0", RED) + number;
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			superNumber = number;
		} else {
			String num = suid;
			if (!MainActivity.LEVEL_COLOR_MAPS.isEmpty()) {
				try {
					num = replaceTextColor(num, num,
							MainActivity.LEVEL_COLOR_MAPS.get(sucolor + "")
							.getColor());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			superNumber = num;
		}
		// }
		try {

			return Html.fromHtml(superNumber.toString());
		} catch(NullPointerException e) {
			return Html.fromHtml("");
		}
	}

	public static String replaceTextColor(String text, String replace,
			String color) {
		if (TextUtils.isEmpty(replace)) {
			return text;
		}
		return text.replace(replace, "<font color=\"" + color + "\">" + replace
				+ "</font>");
	}

	public int getUserid() {
		return userid;
	}

	public void setUserid(int userid) {
		this.userid = userid;
	}

	public static final void setupDoubleLineContactsView(View v,
			ContactsBaseBean base) {
		setupSingleLineContactsView(v, base);
		TextView number = ViewHolder.get(v, R.id.number);
		try {
			number.setText(base.getSuperNumber());
		} catch(NullPointerException e) {

		}
	}

	/**
	 * 返回headerview，基本所有的页面都是这个
	 * 
	 * @param context
	 * @param position
	 * @param convertView
	 * @param parent
	 * @param list
	 * @return
	 */
	public static <T extends ContactsBaseBean> View getHeaderView(Context context,
			int position, View convertView, ViewGroup parent, List<T> list) {
		// TODO Auto-generated method stub
		convertView = LayoutInflater.from(context).inflate(
				R.layout.list_sticky_header_text, parent, false);
		TextView tv = (TextView) convertView;
		tv.setText(list.get(position).getStickyItem());
		return convertView;
	}

	

	public ContactsBaseBean() {

	}

	public String getPhoto() {
		return photo;
	}

	public void setPhoto(String photo) {
		this.photo = photo;
	}

	private String nick_name;

	public String getNick_name() {
		return nick_name;
	}

	public void setNick_name(String nick_name) {
		this.nick_name = nick_name;
	}

	public ContactsBaseBean(Parcel parcel) {
		real_name = parcel.readString();
		nick_name = parcel.readString();
		phone = parcel.readString();
		photo = parcel.readString();
		userid = parcel.readInt();
		type = parcel.readInt();
		sucolor = parcel.readInt();
		unread = parcel.readInt() == 0;
		unreadCount = parcel.readInt();
		suid = parcel.readString();
		onlineday = parcel.readString();
	}

	@Override
	public String getStickyItem() {
		// TODO Auto-generated method stub
		if (TextUtils.isEmpty(nick_name)) {
			return "#";
		}
		return String.valueOf(ShouZiMu.getSpells(nick_name).charAt(0))
				.toUpperCase(Locale.US);
	}

	@Override
	public boolean matches(String str) {
		// TODO Auto-generated method stub
		if (!TextUtils.isEmpty(suid)) {
			return suid.contains(str) || phone.contains(str);
		}
		return phone.contains(str);

		// char[] chars = getPinyin().toCharArray();
		// for (char c : chars) {
		// if (str.contains(String.valueOf(c))) {
		// return true;
		// }
		// }
		// return false;
	}

	@Override
	public int compareTo(ContactsBaseBean another) {
		// TODO Auto-generated method stub
		// if (TextUtils.isEmpty(real_name)
		// || TextUtils.isEmpty(another.real_name)) {
		// return -1;
		// }
		String c1 = getStickyItem();
		if (c1.equals("#")) {
			return -1;
		}
		String c2 = another.getStickyItem();
		if (c2.equals("#")) {
			return 1;
		}
		return c1.compareTo(c2);
	}

	public String getReal_name() {
		return real_name;
	}

	public void setReal_name(String name) {
		this.real_name = name;
	}

	public String getPhone() {
		if (phone == null) {
			return "";
		}
		return phone.replaceAll(" ", "");
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	@Override
	public int describeContents() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		// TODO Auto-generated method stub
		dest.writeString(real_name);
		dest.writeString(nick_name);
		dest.writeString(phone);
		dest.writeString(photo);
		dest.writeInt(userid);
		dest.writeInt(type);
		dest.writeInt(sucolor);
		dest.writeInt(unread ? 0 : 1);
		dest.writeInt(unreadCount);
		dest.writeString(suid);
		dest.writeString(onlineday);
	}

	public List<PinyinUnit> getNamePinyinUnits() {
		if (mNamePinyinUnits.isEmpty()) {
			PinyinUtil.chineseStringToPinyinUnit(nick_name, mNamePinyinUnits);
		}
		return mNamePinyinUnits;
	}

	public void setNamePinyinUnits(List<PinyinUnit> namePinyinUnits) {
		mNamePinyinUnits = namePinyinUnits;
	}

	public void clearMatchKeywords() {

	}

	public void setSearchByType(SearchByType type) {

	}

	public enum SearchByType {
		SearchByNull, SearchByName, SearchByPhoneNumber,
	}
}
